package com.qianchang.microfinance.view.manager;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.SystemClock;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import android.text.TextUtils;

import com.qianchang.microfinance.view.manager.base.BaseViewManager;
import com.dm.library.utils.BitmapUtils;
import com.dm.library.utils.FileUtils;
import com.dm.library.utils.ToastUtil;
import com.dm.library.widgets.SelectPhotoDialog;

import java.io.File;
import java.io.IOException;


/**
 * 版权:深圳市迪蒙网络科技有限公司
 * 描述: 这个类仅仅完成了图片的选择的功能,当选择完图片后，activity的onActivityResult被回调，这个时候也需要调用本类中的onActivityResult方法
 * 否则选择图片的流程会被中断
 * 修改人:<修改人>
 * Created by 朱成 on 2016/12/19.
 */
public abstract class ChooseImageManager extends BaseViewManager {

    public ChooseImageManager(Context context) {
        super(context);
    }

    /**
     * 是否进行裁切
     */
    private boolean crop = true;

    // 图片裁减之后的宽
    protected int imageWidth = 300;
    // 图片裁减之后的高
    protected int imageHeight = 300;
    // 宽高比
    protected int aspectX = 1;
    protected int aspectY = 1;

    public static final int PHOTOHRAPH = 1;// 拍照
    public static final int PHOTOZOOM = 2; // 缩放
    public static final int PHOTORESULT = 3;// 结果
    public static final String IMAGE_UNSPECIFIED = "image/*";
    private static final int REQUEST_CODE_COMMON = 0;


    public void onActivityResult(int requestCode, Intent data) {
        if (null != selectPhotoDialog && selectPhotoDialog.isShowing()) {
            selectPhotoDialog.dismiss();
        }
        switch (requestCode) {
            case REQUEST_CODE_COMMON:
                break;
            case PHOTOHRAPH:// 拍照结束后
//                startPhotoZoom(getUriForFile(mContext, sdcardTempFile));
                pickImage(getUriForFile(mContext, sdcardTempFile), sdcardTempFile);
                break;
            case PHOTOZOOM: // 读取相册缩放图片结束后
                if (data == null) {
                    return;
                }
//                startPhotoZoom(data.getData());
                pickImage(data.getData(), null);
                break;
            case PHOTORESULT: // 处理结果
                if (data == null) {
                    return;
                }
                sdcardTempFile = null;
                onPhotoResult(setPicToView(data));
                setActivityValidateBack(true);
                break;
        }
    }

    private void pickImage(Uri uri, File tempFile) {
        if (crop) {
            startPhotoZoom(uri);
        } else {
            File file;
            if (tempFile != null) {
                file = tempFile;
            } else {
                file = getFileFromMediaUri(mContext, uri);
            }

            if (file != null) {
                Bitmap photoBmp = null;
                try {
                    photoBmp = BitmapUtils.getBitmapFormUri(mContext, Uri.fromFile(file));
                } catch (IOException e) {
                    e.printStackTrace();
                }

                if (photoBmp != null) {
                    int degree = BitmapUtils.getBitmapDegree(file.getAbsolutePath());
                    /**
                     * 把图片旋转为正的方向
                     */
                    Bitmap newbitmap = BitmapUtils.rotateBitmapByDegree(photoBmp, degree);

                    sdcardTempFile = null;
                    onPhotoResult(newbitmap);
                    setActivityValidateBack(true);
                }
            }
        }
    }

    /**
     * 保存裁剪之后的图片数据 将图片设置到imageview中
     *
     * @param picdata 　　　　　　　　　　资源
     */
    public Bitmap setPicToView(Intent picdata) {
        Bundle extras = picdata.getExtras();
        if (extras != null) {
            Bitmap photo = extras.getParcelable("data");
            return photo;
        }
        return null;
    }


    /**
     * 图片被选中完成之后,成功获取到Bitmap对象
     *
     * @param bitmap
     */
    protected abstract void onPhotoResult(Bitmap bitmap);

    /**
     * 裁剪图片
     *
     * @param uri
     */
    protected void startPhotoZoom(Uri uri) {
        setActivityValidateBack(false);
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, IMAGE_UNSPECIFIED);
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", aspectX);
        intent.putExtra("aspectY", aspectY);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", imageWidth);
        intent.putExtra("outputY", imageHeight);
        // 裁剪时是否保留图片的比例
        intent.putExtra("scale", true);
        intent.putExtra("return-data", true);

        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
        intent.putExtra("noFaceDetection", true); // no face detection

        // android7.0
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        }
        getActivity().startActivityForResult(intent, PHOTORESULT);
    }

    private void setActivityValidateBack(boolean b) {
//        if (mContext instanceof BaseActivity) {
//            BaseActivity activity = (BaseActivity) mContext;
//            activity.setValidateBack(b);
//        }
    }

    protected Activity getActivity() {
        if (mContext instanceof Activity) {
            Activity ac = (Activity) mContext;
            return ac;
        } else {
            throw new RuntimeException("你需要传入继承于Activity的context对象进来!");
        }
    }


    protected File sdcardTempFile;
    private SelectPhotoDialog selectPhotoDialog = null;
    private static final String IMAGE_NAME = "tmp_pic_";
    private static final String IMAGE_EXT = ".jpg";

    public void showSelectPhotoDialog() {
        if (null == selectPhotoDialog) {
            selectPhotoDialog = new SelectPhotoDialog(getActivity());
            selectPhotoDialog.setOnViewClickListener(new SelectPhotoDialog.OnViewClickListener() {
                @Override
                public void onSelectPhotoClick() {
                    getImageFromAlbum();
                }

                @Override
                public void onTakePhotoClick() {
                    if (sdcardTempFile == null) {
                        // 头像保存的路径
                        sdcardTempFile =
                                new File(Environment.getExternalStorageDirectory(),
                                        getImageSavePath());
                    }
                    getImageFromCamera();
                }
            });
        }
        selectPhotoDialog.show();
    }

    private String getImageSavePath() {
        return IMAGE_NAME + SystemClock.currentThreadTimeMillis() + IMAGE_EXT;
    }

    /***
     * 从相册选择
     */
    private void getImageFromAlbum() {
        setActivityValidateBack(false);
        Intent intent = new Intent(Intent.ACTION_PICK, null);
        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, IMAGE_UNSPECIFIED);
        getActivity().startActivityForResult(intent, PHOTOZOOM);
    }

    /***
     * 拍照
     */
    private void getImageFromCamera() {
        setActivityValidateBack(false);
        Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
        Uri uri = getUriForFile(mContext, sdcardTempFile);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        getActivity().startActivityForResult(intent, PHOTOHRAPH);
    }

    /**
     * 判断系统版本，获取Uri
     *
     * @param context
     * @param file
     * @return
     */
    private static Uri getUriForFile(Context context, File file) {
        if (context == null || file == null) {
            throw new NullPointerException();
        }
        Uri uri;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            uri = FileProvider.getUriForFile(context.getApplicationContext(), "com.qianchang.microfinance.fileprovider", file);// authority需跟Manifest文件配置的authorities一致
        } else {
            uri = Uri.fromFile(file);
        }
        return uri;
    }

    protected String createFile(Bitmap bitmap) {
        String fileName = System.currentTimeMillis() + "_userImage.jpg";
        String path = FileUtils.getInnerSDCardPath() + "/dimeng/image/";
        String photoPath = FileUtils.createFile(bitmap, path, fileName);

        if (TextUtils.isEmpty(photoPath)) {
            ToastUtil.getInstant().show(mContext, "图片获取失败");
            return null;
        }
        return photoPath;
    }

    /**
     * 选择的图片是否允许裁切
     *
     * @param crop
     */
    public void setCropEnabled(boolean crop) {
        this.crop = crop;
    }


    /**
     * 通过Uri获取文件（Android N以上拍照后获取File失败）
     *
     * @param ac
     * @param uri
     * @return
     */
    public static File getFileFromMediaUri(Context ac, Uri uri) {
        if(uri.getScheme().toString().compareTo("content") == 0){
            String filePath = null;
            String[] proj = { MediaStore.MediaColumns.DATA };
            Cursor cursor = ac.getContentResolver().query(uri, proj, null, null, null);
            if (cursor.moveToFirst()) {
                int columnIndex = cursor.getColumnIndex(proj[0]);
                filePath = cursor.getString(columnIndex);
            }
            cursor.close();

            return new File(filePath);
        } else if (uri.getScheme().toString().compareTo("file") == 0){
            return new File(uri.toString().replace("file://", ""));
        }
        return null;
    }
}
